package com.dream.dao.stock;

/**
 * 
 * @author Evan
 * @date 2013-8-25
 * 
 */
import java.util.List;

import org.springframework.stereotype.Repository;

import com.dream.model.stock.ProductPartStock;
import com.dream.model.stock.ProductPartStock.StockProductType;
import com.dream.utils.hibernate.DetachedCriteriaBuilder;
import com.dream.utils.hibernate.DreamBaseDAO;
import com.dream.utils.hibernate.PagingVO;
import com.dream.vo.stock.ProductPartStockVO;

@Repository
public class ProductPartStockDAO extends DreamBaseDAO<ProductPartStock> {
	
	public PagingVO query(final ProductPartStockVO vo, final PagingVO page){
		
		DetachedCriteriaBuilder queryBuilder = initQueryBuilder(vo);
		DetachedCriteriaBuilder countBuilder = initQueryBuilder(vo);
		return this.selectPagingVO(queryBuilder, page, countBuilder);
		
	}
	
	private DetachedCriteriaBuilder initQueryBuilder(final ProductPartStockVO vo){
		
		DetachedCriteriaBuilder builder = DetachedCriteriaBuilder.instance(ProductPartStock.class);
		builder.innerJoin("productPart", "p").innerJoin("shop", "shop");
		builder.addEq("deleted", false).addEq("stockType", StockProductType.getInstance(vo.getStockType()));
		builder.addEq("shopId", vo.getShopId()).addIn("shopId", vo.getMyShops());
		builder.addEq("productPartId", vo.getProductPartId()).addLikeAny("p.name", vo.getProductPartName());
		builder.addIn("shop.orgId", vo.getOrgs());
		return builder;
		
	}
	
	public List<ProductPartStock> getProductPart(final ProductPartStockVO vo,int topN){
		
		DetachedCriteriaBuilder builder = initQueryBuilder(vo);
		return this.selectTopN(builder,topN);
		
	}
	
	public ProductPartStock getStock(StockProductType type,String shopId,String partId){
		
		DetachedCriteriaBuilder builder = DetachedCriteriaBuilder.instance(ProductPartStock.class);
		builder.addEq("deleted", false).addEq("stockType", type);
		builder.addEq("shopId", shopId);
		builder.addEq("productPartId", partId);
		
		return this.selectTopOne(builder);
		
	}
	
}
